package cn.com.dhc.danlu.fragment;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.com.dhc.danlu.R;
import cn.com.dhc.danlu.fragment.base.BaseBridgeFragment;
import cn.com.dhc.danlu.fragment.bridge.FragmentBridge;
import cn.com.dhc.danlu.util.ToastUtil;

/**
 * @author wuhaiyang
 */
public class ForgetPwdFragment extends BaseBridgeFragment {
    private EditText et_new_pwd;
    private EditText et_confirm_pwd;

    public ForgetPwdFragment () {}

    public static ForgetPwdFragment newInstance (int type) {
        ForgetPwdFragment fragment = new ForgetPwdFragment ();
        Bundle bundle = new Bundle ();
        bundle.putInt ("type", type);
        fragment.setArguments (bundle);
        return fragment;
    }

    @Override
    public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate (R.layout.fragment_forgetpwd, container, false);
    }

    @Override
    public void onActivityCreated (Bundle savedInstanceState) {
        super.onActivityCreated (savedInstanceState);
        et_new_pwd = (EditText) getView ().findViewById (R.id.et_new_pwd);
        et_confirm_pwd = (EditText) getView ().findViewById (R.id.et_confirm_pwd);
        getView ().findViewById (R.id.btn_commit).setOnClickListener (new OnClickListener () {
            @Override
            public void onClick (View v) {
                commitLogic ();
            }
        });
    }

    protected void commitLogic () {
        String pwd = et_new_pwd.getText ().toString ();
        String confirmPwd = et_confirm_pwd.getText ().toString ();
        if (TextUtils.isEmpty (pwd) || TextUtils.isEmpty (confirmPwd)) {
            ToastUtil.getInstance ().show (R.string.input_password_label);
            return;
        }
        if (!pwd.equals (confirmPwd)) {
            ToastUtil.getInstance ().show (R.string.not_equal);
            return;
        }
        if (!isMatch (confirmPwd)) {
            ToastUtil.getInstance ().show (R.string.no_requirement_pwd);
            return;
        }
        mBridgeCallback.onHandle (FragmentBridge.TYPE_RESET_PWD, confirmPwd);
    }

    private boolean isMatch (String confirmPwd) {
        Pattern r = Pattern.compile ("^[A-Za-z0-9]{6,16}$");
        Matcher m = r.matcher (confirmPwd);
        return m.matches ();
    }
}